package com.cloud.pole.tool.controller;

import java.io.File;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.exception.ParamException;
import com.cloud.pole.common.msg.ApiRestResponse;
import com.cloud.pole.common.util.DateUtils;
import com.cloud.pole.common.util.RegexUtils;
import com.cloud.pole.common.util.UUIDUtils;
import com.cloud.pole.tool.config.FileUploadConfiguration;
import io.undertow.server.handlers.form.MultiPartParserDefinition.FileTooLargeException;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/image/front")
@Slf4j
@Configuration
public class FileUploadController {

	@Autowired
	FileUploadConfiguration fileUploadConfiguration;
	
	/**
	 * 上传图片
	 * @param mobile
	 * @param verifyCode
	 * @param templateKey
	 * @return
	 */
	@RequestMapping(value = "/uploadImage")
    @ResponseBody
    public ApiRestResponse<String> uploadImage(HttpServletRequest request, HttpServletResponse response){
		try {
			CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			//设置编码
		    commonsMultipartResolver.setDefaultEncoding("UTF-8");
		    // 判断是否有文件上传
		    if (!commonsMultipartResolver.isMultipart(request)) {
		    	return ApiRestResponse.fail("请选择文件上传！", null);
		    }
		    //commonsMultipartResolver.setMaxUploadSize(10 * 1024 * 1024);
	    	MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			// 获得文件：   
	        MultipartFile imageFile = multiRequest.getFile("imageFile");  
	        if (!commonsMultipartResolver.isMultipart(request)) {
		    	return ApiRestResponse.fail("imageFile不能为空！", null);
		    }
	        String useType = multiRequest.getParameter("useType");
			String originFileName = imageFile.getOriginalFilename();
			ParamException.err(StringUtils.isBlank(useType), "useType不能为空");
			if(!RegexUtils.isImageFile(originFileName)){
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "文件类型错误");
			}
			String filePath = fileUploadConfiguration.getUploadImagePath();
			int pot= originFileName.lastIndexOf(".");        
			filePath = filePath + java.io.File.separator + useType;
			createNotExistsDir(filePath);
			
			Date date = new Date();  
			String strDate = DateUtils.formatDate(date, "yyMMdd");
			String ext = originFileName.substring(pot);   
			String newFileName =  UUIDUtils.generateShortUuid15() + date.getTime() + ext;
			String newFilePath = filePath + java.io.File.separator + newFileName;    
//			String returnFileUrl = fileUploadConfiguration.getImageUrl() +  "/" + useType + "/" + newFileName; 
			String returnFileUrl = "/" + useType + "/" + newFileName; 
            imageFile.transferTo(new File(newFilePath));
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, returnFileUrl);
		} 
		catch(FileTooLargeException e) {
			return ApiRestResponse.fail("文件太大", null);
		}
		catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
	}
	
	 /**
	  * 先判断目录是否存在，如果不存在，则先建立目录
     *
     * @param path
     * @return
     */
    public static boolean createNotExistsDir(String path) {
        if (path == null || path.length() < 1) {
            return false;
        }
        java.io.File myfile = new java.io.File(path);
        if (myfile.exists() == false) {
            return myfile.mkdirs();
        }
        return true;
    }
}
